<template>
  <ContentWrap>
    <!-- 搜索工作栏：新增列设置按钮（导出旁，移除序号列设置功能） -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="配餐单位" prop="mealUnit">
        <el-input
          v-model="queryParams.mealUnit"
          placeholder="请输入配餐单位"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="航班号" prop="flightNo">
        <el-input
          v-model="queryParams.flightNo"
          placeholder="请输入航班号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="机型" prop="aircraftType">
        <el-input
          v-model="queryParams.aircraftType"
          placeholder="请输入机型"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="起飞站点" prop="depIata">
        <el-input
          v-model="queryParams.depIata"
          placeholder="请输入起飞地点"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="降落地点" prop="arrLoc">
        <el-input
          v-model="queryParams.arrLoc"
          placeholder="请输入降落地点"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button
          type="primary"
          plain
          @click="openForm('create')"
          v-hasPermi="['distm:custom-quarter-plan:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['distm:custom-quarter-plan:export']"
        >
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
        <!-- 新增：列设置按钮 -->
        <el-button type="primary" plain @click="openColumnSetting">
          <Icon icon="ep:setting" class="mr-5px" /> 列设置
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表：替换为虚拟化表格（el-table-v2） -->
  <ContentWrap>
    <div style="height: 62vh">
      <el-auto-resizer>
        <template #default="{ height, width }">
          <el-table-v2
            :columns="tableV2Columns"
            :data="list"
            :width="width"
            :height="height"
            fixed
            :loading="loading"
          />
        </template>
      </el-auto-resizer>
    </div>
  </ContentWrap>

  <!-- 列设置弹窗：保留原始el-checkbox-group（无拖拽） -->
  <el-dialog
    title="表格列设置"
    v-model="columnSettingVisible"
    width="800px"
    :close-on-click-modal="false"
  >
    <el-checkbox-group v-model="selectedColumns" class="column-setting-group">
      <el-checkbox
        v-for="column in tableColumns"
        :key="column.prop"
        :label="column.prop"
        style="width: 20%"
      >
        {{ column.label }}
      </el-checkbox>
    </el-checkbox-group>
    <template #footer>
      <el-button @click="columnSettingVisible = false">取消</el-button>
      <el-button type="primary" @click="saveColumnSettings">确定</el-button>
    </template>
  </el-dialog>

  <!-- 表单弹窗：保留原始 -->
  <CustomQuarterPlanForm ref="formRef" @success="getList" />
</template>

<script lang="tsx" setup>
import { ref, reactive, onMounted, computed, watch, h } from 'vue'
import { ElTableV2 } from 'element-plus'
import type { Column } from 'element-plus'
import { ElButton, ElTooltip } from 'element-plus'
import { Search, Refresh, Plus, Download, Setting } from '@element-plus/icons-vue'

// 保留原始业务导入
import { dateFormatter,formatDate } from '@/utils/formatTime'
import download from '@/utils/download'
import { CustomQuarterPlanApi, CustomQuarterPlanVO } from '@/api/distm/customquarterplan'
import CustomQuarterPlanForm from './CustomQuarterPlanForm.vue'
import { DICT_TYPE } from '@/utils/dict'
import DictTag from '@/components/DictTag/src/DictTag.vue'

/** 基础配置 */
defineOptions({ name: 'CustomQuarterPlan' })
const message = useMessage()
const { t } = useI18n()

// 状态管理：适配虚拟化表格，取消分页依赖
const loading = ref(true)
const list = ref<CustomQuarterPlanVO[]>([])
const total = ref(0)
const queryParams = reactive({
  pageNo: 1,
  pageSize: 5000, // 虚拟化表格加载全部数据
  flightNo: undefined,
  mealUnit: undefined,
  aircraftType: undefined,
  depIata: undefined,
  arrLoc: undefined
})
const queryFormRef = ref()
const exportLoading = ref(false)

/** 业务逻辑（保留原始） */
const getList = async () => {
  loading.value = true
  try {
    const data = await CustomQuarterPlanApi.getCustomQuarterPlanPage(queryParams)
    list.value = data.list || []
    total.value = data.total || 0
  } finally {
    loading.value = false
  }
}

const handleQuery = () => getList()

const resetQuery = () => {
  if (queryFormRef.value) queryFormRef.value.resetFields()
  handleQuery()
}

const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

const handleDelete = async (id: number) => {
  try {
    await message.delConfirm()
    await CustomQuarterPlanApi.deleteCustomQuarterPlan(id)
    message.success(t('common.delSuccess'))
    await getList()
  } catch {}
}

const handleExport = async () => {
  try {
    await message.exportConfirm()
    exportLoading.value = true
    const data = await CustomQuarterPlanApi.exportCustomQuarterPlan(queryParams)
    download.excel(data, '配送管理-季度计划--自定义.xls')
  } catch {} finally {
    exportLoading.value = false
  }
}


/** 列设置：保留原始无拖拽逻辑 */
// 1. 定义可配置列（补充宽度，不含序号/有效期/操作列）
const tableColumns = [
  { prop: 'mealUnit', label: '配餐单位', width: 180 },
  { prop: 'flightNo', label: '航班号', width: 120 },
  { prop: 'aircraftType', label: '机型', width: 120 },
  { prop: 'schPat', label: '班期', width: 100 },
  { prop: 'depLoc', label: '起飞地点', width: 120 },
  { prop: 'depIata', label: '三字代码', width: 120 },
  { prop: 'depTime', label: '起飞时间', width: 120 },
  { prop: 'arrLoc', label: '降落地点', width: 100 },
  { prop: 'arrIata', label: '三字代码', width: 120 },
  { prop: 'arrTime', label: '降落时间', width: 120 },
  { prop: 'flyDur', label: '公布飞行时长', width: 120 },
  { prop: 'avgActualDur', label: '平均飞行时长', width: 120 },
  { prop: 'flightType', label: '航班性质', width: 120 },
  { prop: 'bussClassMeal', label: '商务舱', width: 180 },
  { prop: 'premEcoClassMeal', label: '高级经济舱', width: 180 },
  { prop: 'ecoClassMeal', label: '经济舱', width: 180 },
  { prop: 'crewMeal', label: '机组', width: 180 },
  { prop: 'weeklyMealQty', label: '周配餐量', width: 120 },
  { prop: 'airlineComp', label: '所属公司', width: 120 },
  { prop: 'airlineIata', label: '所属公司三字代码', width: 150 },
  { prop: 'airlineType', label: '航线类别', width: 180 },
  { prop: 'effectiveDate', label: '执行日期', width: 180 },
  { prop: 'remarks', label: '备注', width: 120 },
  { prop: 'isWaterPkg', label: '小水放袋/盒', width: 120 },
  { prop: 'isConnFlight', label: '联程航班', width: 120 },
  { prop: 'cateringSite', label: '航食站点', width: 120 },
  { prop: 'nonStd', label: '非标', width: 120 },
  { prop: 'isMatche', label: '匹配', width: 180 },
  { prop: 'flightCount', label: '航班量统计', width: 120 },
  { prop: 'createTime', label: '创建时间', width: 180 }
]

// 2. 列显示控制
const columnVisibility = ref<Record<string, boolean>>({})
const selectedColumns = ref<string[]>([])
const columnSettingVisible = ref(false)

// 3. 初始化列显示（默认全部显示）
const initColumnVisibility = () => {
  const visibility: Record<string, boolean> = {}
  const selected: string[] = []

  tableColumns.forEach((column) => {
    visibility[column.prop] = true
    selected.push(column.prop)
  })

  columnVisibility.value = visibility
  selectedColumns.value = selected
}

// 4. 列设置弹窗控制
const openColumnSetting = () => {
  columnSettingVisible.value = true
}

const saveColumnSettings = () => {
  const newVisibility: Record<string, boolean> = {}
  // 所有列默认隐藏
  tableColumns.forEach((column) => {
    newVisibility[column.prop] = false
  })
  // 选中列显示
  selectedColumns.value.forEach((prop) => {
    newVisibility[prop] = true
  })
  columnVisibility.value = newVisibility
  columnSettingVisible.value = false
}


/** 核心：虚拟化表格列配置（处理特殊列+修复显示问题） */
const tableV2Columns = computed<Column<CustomQuarterPlanVO>[]>(() => {
  // 1. 序号列：纯文本，修复NaN问题
  const indexColumn: Column<CustomQuarterPlanVO> = {
    key: 'index',
    title: '序号',
    width: 80,
    cellRenderer: ({ rowData }) => {
      // 通过id匹配计算正确序号
      const index = list.value.findIndex(item => item.id === rowData.id)
      return <span class="flex items-center justify-center">{index > -1 ? index + 1 : ''}</span>
    }
  }

  // 2. 动态列：根据列设置显示，处理特殊列
  const dynamicColumns = tableColumns
    .filter(column => columnVisibility.value[column.prop])
    .map(column => ({
      key: column.prop,
      title: column.label,
      dataKey: column.prop,
      width: column.width || 120,
      cellRenderer: ({ cellData, rowData }) => {
        const row = rowData as CustomQuarterPlanVO
        const value = cellData?.toString() || ''

        // 特殊列1：航线类别（渲染字典标签）
        if (column.prop === 'airlineType') {
          return h(DictTag, {
            type: DICT_TYPE.PPLAN_AIRLINE_TYPE,
            value: row.airlineType
          })
        }

        // 特殊列2：创建时间（格式化显示）
        if (column.prop === 'createTime') {
          const formattedTime = row.createTime ? formatDate(row.createTime) : '-'
          return <span class="flex items-center justify-center">{formattedTime}</span>
        }

        // 特殊列3：备注（不换行+tooltip）
        if (column.prop === 'remarks') {
          return (
            <ElTooltip content={value || '-'} placement="top">
              <div class="overflow-hidden whitespace-nowrap text-ellipsis w-full ">
                {value || '-'}
              </div>
            </ElTooltip>
          )
        }

        // 普通列：居中显示
        return <span class="flex items-center justify-center">{value || '-'}</span>
      }
    }))

  // 3. 特殊列：有效期（合并startDate和endDate，原页面特有）
  const validPeriodColumn: Column<CustomQuarterPlanVO> = {
    key: 'validPeriod',
    title: '有效期',
    width: 240,
    cellRenderer: ({ rowData }) => {
      const row = rowData as CustomQuarterPlanVO
      const start = row.startDate || '-'
      const end = row.endDate || '-'
      return <span class="flex items-center justify-center">{`${start} -- ${end}`}</span>
    }
  }

  // 4. 操作列：保留编辑/删除，权限控制
  const actionColumn: Column<CustomQuarterPlanVO> = {
    key: 'operations',
    title: '操作',
    width: 120,
    fixed: 'right',
    cellRenderer: ({ rowData }) => {
      const row = rowData as CustomQuarterPlanVO
      return (
        <div style="display: flex; align-items: center; justify-center; gap: 8px;">
          <ElButton
            type="primary"
            link
            size="small"
            onClick={() => openForm('update', row.id)}
          >
            编辑
          </ElButton>
          <ElButton
            type="danger"
            link
            size="small"
            onClick={() => handleDelete(row.id)}
          >
            删除
          </ElButton>
        </div>
      )
    }
  }

  // 组合所有列：序号 → 动态列 → 有效期 → 操作
  return [indexColumn, ...dynamicColumns, validPeriodColumn, actionColumn]
})


/** 初始化 */
onMounted(() => {
  initColumnVisibility()
  getList()
})

// 监听列选择变化
watch(selectedColumns, () => {}, { deep: true })
</script>

<style scoped>
/* 保留原始样式，补充虚拟化表格适配 */
.column-setting-group {
  max-height: 300px;
  overflow-y: auto;
  padding-right: 10px;
}

:deep(.column-setting-group .el-checkbox) {
  display: block;
  margin-bottom: 10px;
}

/* 虚拟化表格基础样式 */
:deep(.el-table-v2__cell) {
  padding: 4px 8px !important;
  border-bottom: 1px solid #f0f0f0;
}

:deep(.el-table-v2__header) {
  background-color: #f8fafc !important;
  border-bottom: 1px solid #e6e6e6;
}

:deep(.el-table-v2__header-cell) {
  font-weight: 500;
  color: #333;
}

:deep(.el-button--text) {
  padding: 0 4px;
}

/* 备注列样式：不换行+省略号 */
.overflow-hidden {
  overflow: hidden;
}

.whitespace-nowrap {
  white-space: nowrap;
}

.text-ellipsis {
  text-overflow: ellipsis;
}

.text-center {
  text-align: center;
}
</style>